#include "main.h"
#include "i2c.h"
#include "i2c_hal.h"
#include "M24C04.h"

void M24C04_Write(uint8_t address, uint8_t data)
{
	I2CStart();
	
	I2CSendByte(M24C04_LOW_W_ADDRESS);
	if(I2CWaitAck() == ERROR)
		HAL_GPIO_WritePin(LED_32_GPIO_Port,LED_32_Pin,GPIO_PIN_SET);
	
	I2CSendByte(address);
	I2CWaitAck();
	
	I2CSendByte(data);
	I2CWaitAck();
	
	I2CStop();
}

void M24C04_Read(uint8_t address, uint8_t* data)
{
	int a = 3;
	I2CStart();
	
	I2CSendByte(M24C04_LOW_W_ADDRESS);
	if(I2CWaitAck() == ERROR)
		HAL_GPIO_WritePin(LED_32_GPIO_Port,LED_32_Pin,GPIO_PIN_RESET);
	
	I2CSendByte(address);
	I2CWaitAck();
	
	I2CStart();
	
	I2CSendByte(M24C04_LOW_R_ADDRESS);
	I2CWaitAck();
	
	while(1)
	{
		*data = I2CReceiveByte();
		if(a > 0){
			I2CSendAck();
			data++;
			a--;
		}else
		{
			I2CSendNotAck();
			break;
		}
	}
	
	I2CStop();
}
